<template>
  <base-breadcrumb :state="state" v-loading="loading">
    <b-steps :current="stepVal" direction="vertical" @change.self="stepChange">
      <b-step title="基本信息">
        <a-card v-if="activeKey[0]" slot="description" :bordered="false">
          <a-form-model ref="ruleForm" :rules="rules" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-row>
              <a-col span="8">
                <a-form-model-item label="合同编号" prop="code">
                  <BaseInput v-model="formData.code" @blur="checkRepeat" />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="工程名称" prop="constructionTypeId">
                  <BSelect v-model="formData.constructionTypeId" :request="()=>selectOption({type: 18     })" />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同名称">
                  <BaseInput v-model="formData.name" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="供应商名称">
                  <BaseInput v-model="formData.supplier" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="供应商编码">
                  <BaseInput v-model="formData.supplierCode" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同类别" prop="contractTypeId">
                  <a-select v-model="formData.contractTypeId" placeholder="请选择" @change="typeLabelChange">
                    <a-select-option v-for="item in typeArr" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8" v-if="formData.contractTypeCode !=='140001' && formData.contractTypeCode !=='140006'">
                <a-form-model-item label="材料类别" prop="materialClassId">
                  <BSelect
                    :form="formData"
                    keyValue="contractTypeCode"
                    v-model="formData.materialClassId"
                    :request="typeLabel(36)"
                  />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同文本" prop="textId">
                  <a-select v-model="formData.textId" placeholder="请选择">
                    <a-select-option v-for="item in textArr" :key="item.id + '1'" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="前期招标资料" prop="preBidFiles">
                  <a-select v-model="formData.preBidFiles" placeholder="请选择">
                    <a-select-option :value="1">具备</a-select-option>
                    <a-select-option :value="0">不具备</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="对方签约授权委托" prop="delegation">
                  <a-select v-model="formData.delegation">
                    <a-select-option :value="1">具备</a-select-option>
                    <a-select-option :value="0">不具备</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="联系人" prop="contactsPeople">
                  <BaseInput v-model="formData.contactsPeople" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="电话" prop="contactsTel">
                  <BaseInput v-model="formData.contactsTel" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="材料工程师">
                  <BaseInput v-model="formData.supervisorEng" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="数量总额">
                  <BaseInput v-model="formData.numberTotal" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同价款总额(税前)(元)">
                  <BaseInput v-model="formData.contractNumberPriceTotal" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="总收益金额(元)">
                  <BaseInput v-model="formData.incomeAmountTotal" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="总利润率" prop="size">
                  <BaseInput v-model="formData.profitRateTotal" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                  <a-form-model-item label="所属单位">
                    <BaseInput v-model="formData.branchCompanyName + '/' + formData.projectName" disabled />
                  </a-form-model-item>
                </a-col>
              <!-- <a-col span="8">
                <a-form-model-item label="项目名称">
                  <BaseInput v-model="formData.projectName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="分公司名称">
                  <BaseInput v-model="formData.branchCompanyName" disabled />
                </a-form-model-item>
              </a-col> -->
              <a-col span="8">
                <a-form-model-item label="甲方">
                  <BaseInput v-model="formData.firstParty" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同生效日期">
                  <BaseInput v-model="formData.startDate" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同终止日期">
                  <BaseInput v-model="formData.endDate" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同签订日期">
                  <BaseInput v-model="formData.signDate" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="付款方式">
                  <BaseInput v-model="formData.payTypeStr" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="合同种类">
                  <BaseInput v-model="formData.typeName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="是否采集">
                  <BaseInput v-model="formData.collectName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="用印日期">
                  <BaseInput v-model="formData.applyDate" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="补录人">
                  <BaseInput v-model="formData.creatorName" disabled />
                </a-form-model-item>
              </a-col>
              <a-col span="8">
                <a-form-model-item label="补录时间">
                  <BaseInput v-model="formData.modifiedTime" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
          <div class="pub-next-btn">
            <a-button v-if="state !== 3" :loading="loading" type="primary" @click="temporaryStorage()">
              保存
            </a-button>
            <a-button type="primary" @click="temporaryStorage(true)">
              下一步
            </a-button>
          </div>
        </a-card>
      </b-step>
      <b-step title="合同明细">
        <a-card v-if="activeKey[1] && isSubmit" slot="description" :bordered="false">
          <materials :is-amend-record="true" :id="formData.id || null" :state="state" />
          <div class="pub-next-btn">
            <a-button type="primary" @click="previous">上一步</a-button>
            <a-button type="primary" @click="next">下一步</a-button>
          </div>
        </a-card>
      </b-step>
      <b-step title="相关附件">
        <a-card v-show="activeKey[2]" slot="description" :bordered="false">
          <u-table
            :isShow="state !== 3"
            :deleteUrl="fileDel"
            :uploadList="addFile"
            :list-url="fileList" :business-id="formData.id || null" business-code="MM09"
          />
          <div class="pub-next-btn">
            <a-button type="primary" @click="previous">上一步</a-button>
          </div>
        </a-card>
      </b-step>
    </b-steps>
    <div class="pub-header-btn page-btn-right-top">
      <a-button type="primary" @click="save(false,'AMEND_RECORD',true)">保存草稿</a-button>
      <a-button type="primary" @click="submit('SUBMITTED')">提交</a-button>
      <a-button @click="handleClose">关闭</a-button>
    </div>
    <person-list
      ref="personList"
      @getPerson="getPerson"
    />
  </base-breadcrumb>
</template>
<script>
import { parameterEdit, findListByMainId, submitApply } from '@/api/material/contract/parameter'
import materials from './components/materials/materials'
import { selectOption } from '@/api/material/goods/goods'
import { addFile, fileDel, fileList } from '@/api/material/contract/review'
import ProjectDepTree from '@/components/ProjectDepTree'

export default {
  name: 'a' + Date.now(),
  components: {
    materials,
    ProjectDepTree
  },
  data() {
    return {
      selectOption,
      activeKey: [true, false, false, false, false, false, false],
      loading: false,
      stepVal: 0,
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      state: 2,
      isSubmit: false,
      formData: {
        id: '',
        code: '',
        name: '',
        supplier: null,
        supplierCode: null,
        contractTypeId: null,
        contractTypeCode: null,
        textId: null,
        sourceId: null,
        contactsPeople: '测试联系人',
        contactsTel: '测试电话',
        supervisor: '',
        contractPriceTotal: '',
        numberTotal: '',
        contractNumberPriceTotal: '',
        materialClassId: '',
        materialClassName: '',
        settlePriceTotal: '',
        incomeAmountTotal: '',
        profitRateTotal: '',
        projectName: '',
        projectCode: '',
        branchCompanyName: '',
        branchCompanyCode: '',
        supervisorEng: '',
        isPreBidFiles: null,
        isDelegation: null,
        contactsPeopleId: 1,
        supplierId: null,
        creatorName: this.$userInfo().name,
        modifiedTime: this.$dateFormat(Date.now(), 'D'),
        fromStatus: 1
      },
      rules: {
        materialClassId: { required: true, message: '请选择材料类别', trigger: 'change' },
        code: { required: true, message: '请填写合同编号', trigger: 'blur' },
        constructionTypeId: { required: true, message: '请填写工程名称', trigger: 'blur' },
        contractTypeId: { required: true, message: '请选择合同类别', trigger: 'change' },
        textId: { required: true, message: '请选择合同文本', trigger: 'change' },
        preBidFiles: { required: true, message: '请选择前期招标资料', trigger: 'change' },
        delegation: { required: true, message: '请选择对方签约授权委托', trigger: 'change' }
      },
      sourceArr: [],
      typeArr: [],
      textArr: [],
      isNext: false,
      fileList: fileList(),
      addFile: addFile(),
      fileDel: fileDel(),
      typeLabel: (type) => {
        return async () => {
          let res = await selectOption({ type })
          if (res.code === this.SUCCESS_CODE) {
            if (res.data instanceof Array) {
              return { code: 200, data: res.data.filter(v => v.code === this.formData.contractTypeCode) }
            }
            return { code: 200, data: [] }
          }
          return { code: 500 }
        }
      }
    }
  },
  watch: {
    stepVal(newVal, oldVal) {
      this.$set(this.activeKey, newVal, true)
    }
  },
  created: async function() {
    await this.getSource()
    await this.getType()
    await this.getText()
    this.formData.id = this.$route.query.id
    this.$nextTick(() => {
      if (this.state !== 1) {
        this.getEditInfo()
        this.isSubmit = true
        // _this.$refs.materials.list();
      }
    })
  },
  methods: {

    typeLabelChange(e) {
      this.formData.materialClassName = this.formData.materialClassId = ''
      let res = this.typeArr.find(v => v.id === e)
      if (res) {
        this.formData.contractTypeCode = res.code
      }
    },
    async checkRepeat() {
      let temp = this.$clone(this.formData)

      if (temp.delegation !== null) {
        temp.isDelegation = temp.delegation = temp.delegation === 1
      }
      if (temp.preBidFiles !== null) {
        temp.isPreBidFiles = temp.preBidFiles = temp.preBidFiles === 1
      }
      await parameterEdit(temp)
    },
    getPerson: function(row) {
      this.formData.supervisorEng = row.name
      this.formData.supervisorEngId = row.id
    },
    handleClose() {
      this.$close()
    },
    previous: function() {
      this.isNext = true
      this.stepVal--
      if (this.stepVal < 0) {
        this.stepVal = 0
      }
    },
    onSearch: function(val) {
      // this.$refs.review.open();
    },
    getSource: function() {
      let _this = this
      selectOption({
        type: 13
      }).then((res) => {
        if (res.code === 200) {
          _this.sourceArr = res.data
          _this.formData.sourceId = _this.sourceArr[0].id
        }
      })
    },
    async getType() {
      let res = await selectOption({ type: 14 })
      if (res.code === 200) {
        this.typeArr = res.data
        this.formData.contractTypeId = this.typeArr[0].id
        this.formData.contractTypeCode = this.typeArr[0].code
      }
    },
    getText: function() {
      let _this = this
      selectOption({
        type: 9
      }).then((res) => {
        if (res.code === 200) {
          _this.textArr = res.data
          _this.formData.textId = _this.textArr[0].id
        }
      })
    },
    stepChange: function(val) {
      if (!this.formData) {
        if (val) {
          this.$message.warning('切换步骤前请先填写基本信息')
          this.stepVal = 0
        }
      } else {
        if (!this.isNext) {
          this.$set(this.activeKey, val, !this.activeKey[val])
        }
      }
      this.isNext = false
    },
    // 获取编辑回显数据
    async getEditInfo() {
      this.loading = true
      let res = await findListByMainId({ id: this.formData.id })
      if (res.code === 200) {
        this.formData = { ...this.formData, ...res.data }
        this.formData.fromStatus = 1
        console.log(this.formData)
        if (this.formData.delegation !== null) {
          this.formData.delegation = this.formData.delegation ? 1 : 0
        }
        if (this.formData.preBidFiles !== null) {
          this.formData.preBidFiles = this.formData.preBidFiles ? 1 : 0
        }
        if (!this.formData.creatorName) {
          this.formData.creatorName = this.$userInfo().name
        }
        let res2 = this.typeArr.find(v => v.id === this.formData.contractTypeId)
        if (res2) {
          this.formData.contractTypeCode = res2.code
        }
      }
      this.loading = false
    },
    async submit() {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          if (await this.save(false, 'AMEND_RECORD', false)) {
            let res = await submitApply({ baseId: this.formData.id, auditStatus: 'SUBMITTED' })
            if (res.code === 200) {
              this.$message.success('操作成功')
              this.$close()
            }
          }
        } else {
          this.$noticeWarning('请填写完整')
        }
      })
    },
    async save(isNext, status, showNotice) {
      return new Promise(async resolve => {
        this.loading = true
        let temp = this.$clone(this.formData)
        temp.auditStatus = status
        temp.accountStatus = status
        temp.fromStatus = 1

        if (temp.delegation !== null) {
          temp.isDelegation = temp.delegation = temp.delegation === 1
        }
        if (temp.preBidFiles !== null) {
          temp.isPreBidFiles = temp.preBidFiles = temp.preBidFiles === 1
        }
        let res = await parameterEdit(temp)
        this.loading = false
        if (res.code === 200) {
          showNotice && this.$message.success('操作成功')
          this.isSubmit = true
          isNext && this.next()
          resolve(true)
        }
      })
    },
    async temporaryStorage(isNext) {
      this.loading = true
      let temp = this.$clone(this.formData)
      if (temp.delegation !== null) {
        temp.isDelegation = temp.delegation = temp.delegation === 1
      }
      if (temp.preBidFiles !== null) {
        temp.isPreBidFiles = temp.preBidFiles = temp.preBidFiles === 1
      }
      let res = await parameterEdit(temp)
      this.loading = false
      if (res.code === 200) {
        this.$message.success('操作成功')
        this.isSubmit = true
        isNext && this.next()
      }
    },
    next: function(val) {
      this.isNext = true
      this.stepVal++
    }
  }
}
</script>
